/*
 * @Description: 层级组件reducer
 * @Author: Rfan
 * @Date: 2022-06-21 10:25:48
 * @LastEditTime: 2022-11-04 10:14:37
 */

import {
  ADD_LIST_ITEM,
  DELETE_LIST_ITEM,
  EDIT_LIST_ITEM,
  INIT_INFO,
  SET_CHANGE_METHOD,
  SET_COMPUTE_HEIGHT_SWITCH,
  SET_ENTRY_LIST,
  SET_LIST_HEIGHT,
  SET_SELECTED_ITEM,
  GET_GROUP_LIST,
  SET_FILTER_FIELDS,
  SET_LIST_QUERY
} from '../constants';
import { delItemByIdArray, editItemById, insertItemAfter } from '@/utils/list';

export const LevelTableReducer = (state, action) => {
  switch (action.type) {
    /**
     * @description: 表格选中的项目
     */
    case SET_SELECTED_ITEM:
      return { ...state, selectItems: action.data };

    /**
     * @description: 初始化接收的坐标及上级条目信息
     */
    case INIT_INFO: {
      const { base: baseInfo, upper: upperInfo, fields, fetchMethod } = action;
      return { ...state, baseInfo, upperInfo, upperFields: fields || [], fetchMethod };
    }

    /**
     * @description: 设置条目列表
     */
    case SET_ENTRY_LIST: {
      return { ...state, list: action.list };
    }

    /**
     * @description: 设置请求参数
     */
    case SET_LIST_QUERY: {
      return { ...state, listQuery: action.data };
    }

    /**
     * @description: 设置是否计算高度开关
     */
    case SET_COMPUTE_HEIGHT_SWITCH: {
      return { ...state, isComputeHeight: action.data };
    }

    /**
     * @description: 设置表格高度
     */
    case SET_LIST_HEIGHT: {
      return { ...state, tableHeight: action.data };
    }

    /**
     * @description: 初始化接收的坐标及上级条目信息
     */
    case SET_CHANGE_METHOD:
      return { ...state, selectChange: action.data };

    /**
     * @description: 设置筛选字段
     */
    case SET_FILTER_FIELDS: {
      return {
        ...state,
        filterFields: action.data
      };
    }

    /**
     * @description: 增加列表条目
     */
    case ADD_LIST_ITEM: {
      const { data } = action;
      return {
        ...state,
        list: insertItemAfter(data, state.list)
      };
    }
    case GET_GROUP_LIST: {
      return { ...state, groupList: action.data };
    }

    /**
     * @description: 增加列表条目
     */
    case EDIT_LIST_ITEM: {
      const { id, data } = action;
      return {
        ...state,
        list: editItemById(id, data, state.list)
      };
    }

    /**
     * @description: 初始化接收的坐标及上级条目信息
     */
    case DELETE_LIST_ITEM:
      return {
        ...state,
        list: delItemByIdArray(action.ids, state.list)
      };

    default:
      console.log('untouched', action);
      return state;
  }
};
